// @ts-ignore
// @ts-ignore
import {
  applyInterface,
  queryById2, queryInterfaceById,
  queryInvokeCountByPage,
} from '@/services/ant-design-pro/interfaceInfoController';
import { PageContainer, ProList } from '@ant-design/pro-components';
import {Badge, Button, Checkbox, Drawer, message, Modal, Table, Typography} from 'antd';
import React, { useEffect, useState } from 'react';
import InterfaceInfoDrawer from "@/components/Interface";

const { Paragraph, Title } = Typography;

enum InterfaceStatusEnum {
  OFF = 0,
  OPEN = 1
}
const renderBadge = (count: number, active = false) => {
  return (
    <Badge
      count={count}
      style={{
        marginTop: -2,
        marginLeft: 4,
        color: active ? '#1890FF' : '#999',
        backgroundColor: active ? '#E6F7FF' : '#eee',
      }}
    />
  );
};

export default () => {
  const [activeKey, setActiveKey] = useState<React.Key | undefined>('all');

  const [interfaceInfoList, setInterfaceInfoList] = useState<API.InterfaceInfoVO[]>();
  const [pageRequest, setPageRequest] = useState<PageRequest>();
  const listInterfaceInfo = (params: API.QueryCountRequest) => {
    queryInvokeCountByPage({
      type: activeKey as string,
      ...params,
    }).then((res: any) => {
      if (res?.code === 200) {
        let records = res?.data?.records || []
        records = records.map(item=>{
          const content = [
            {
              label: "总调用",
              value: item?.invokeTotal
            },
            {
              label: "日调用",
              value: item?.invokeDayTotal
            },
            {
              label: "状态",
              value: item?.status === InterfaceStatusEnum.OFF ? "关闭" : "开启",
              status: item?.status === InterfaceStatusEnum.OFF ? "error" : "success"
            },
          ]

          return {
            id:item?.id,
            name:item?.name,
            description:item?.description,
            isApply: item?.isApply,
            content
          }
        })
        setInterfaceInfoList([...records]);
        setPageRequest({
          current: res?.data?.current,
          pageSize: res?.data?.size,
          total: res?.data?.total,
        });
        return;
      }
      message.error(res?.message);
    });
  };

  useEffect(() => {
    listInterfaceInfo({});
  }, []);

  const [openDrawer, setOpenDrawer] = useState(false);

  const [interfaceInfo, setInterfaceInfo] = useState<API.InterfaceInfoEntity>();
  const showDrawer = async (id: string) => {
    const res = await queryInterfaceById({
      id,
    });
    if (res?.code === 200) {
      setInterfaceInfo({
        ...res.data,
      });
      setOpenDrawer(true);
      return;
    }
    message.error(res?.message);
  };

  const onClose = () => {
    setOpenDrawer(false);
  };
  const requestHeaderColumns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    },
  ];
  const requestParamColumns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '必填',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '类型',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '说明',
      key: 'tags',
      dataIndex: 'tags',
    },
  ];

  const responseParamColumns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '说明',
      key: 'tags',
      dataIndex: 'tags',
    },
  ];

  /**
   * 申请接口相关
   * ----------------------
   */
  const [isApplyModalOpen, setIsApplyModalOpen] = useState(false);
  const [currentInterfaceDetail,setCurrentInterfaceDetail] = useState<API.InterfaceInfoVO>()
  const [isAgree,setIsAgree] = useState(false)
  const applyInterfaceById = async (record:API.InterfaceInfoVO) => {

    const res = await applyInterface({
      id: record?.id,
      isAgree
    })
    if (res?.code === 200){
      message.success("申请成功")
      await listInterfaceInfo({})
      return;
    }
    message.error(res?.message)
  }
  const showApplyModal = (record:API.InterfaceInfoVO) => {
    setCurrentInterfaceDetail({
      ...record
    })
    setIsApplyModalOpen(true);
  };
  const handleApplyOk = async () => {
    if (!isAgree){
      message.error("请先同意API使用协议")
      return;
    }
    await applyInterfaceById(currentInterfaceDetail)
    setIsApplyModalOpen(false);
  };
  const handleApplyCancel = () => {
    setIsAgree(false)
    setIsApplyModalOpen(false);
  };

  return (
    <PageContainer title={false}>
      <ProList<any>
        rowKey="id"
        dataSource={interfaceInfoList}
        pagination={{
          ...pageRequest,
          showSizeChanger: true,
          hideOnSinglePage:true,
          onChange: (current, pageSize) => {
            listInterfaceInfo({
              current,
              pageSize,
            });
          },
        }}
        metas={{
          title: {
            dataIndex: 'name',
          },
          description: {
            dataIndex: 'description',
          },
          content: {
            dataIndex: 'content',
            render: (text) => (
              <div key="label" style={{ display: 'flex', justifyContent: 'space-around' }}>
                {(text as any[]).map((t) => (
                  <div key={t.label}>
                    <div style={{ color: '#00000073' }}>{t.label}</div>
                    <div style={{ color: '#000000D9' }}>
                      {t.status === 'success' && (
                        <span
                          style={{
                            display: 'inline-block',
                            width: 8,
                            height: 8,
                            borderRadius: '50%',
                            backgroundColor: '#52c41a',
                            marginRight: 8,
                          }}
                        />
                      )}
                      {t.value}
                    </div>
                  </div>
                ))}
              </div>
            ),
          },
          actions: {
            render: (text, row: API.InterfaceInfoVO) => [
              activeKey === 'all' ? (
                  !row?.isApply
                    ?
                    <Button key="apply" type={'primary'} onClick={() => showApplyModal(row)}>
                      申请
                    </Button>
                    :<Button disabled={row?.isApply} key="apply" type={'primary'} >
                      拥有
                    </Button>
              ) : (
                <Button key="apply" type={'primary'} onClick={() => showDrawer(row?.id as string)}>
                  预览
                </Button>
              ),
            ],
          },
        }}
        toolbar={{
          menu: {
            activeKey,
            items: [
              {
                key: 'all',
                label: (
                  <span>
                    全部接口
                    {activeKey === 'all' &&
                      renderBadge(pageRequest?.total || 0, activeKey === 'all')}
                  </span>
                ),
              },
              {
                key: 'apply',
                label: (
                  <span>
                    已申请
                    {activeKey === 'apply' &&
                      renderBadge(interfaceInfoList?.length || 0, activeKey === 'apply')}
                  </span>
                ),
              },
            ],
            onChange(key) {
              setActiveKey(key);
              listInterfaceInfo({
                type: key as string,
              });
            },
          },
          search: {
            onSearch: (value: string) => {
              listInterfaceInfo({
                name: value,
              });
            },
          },
          actions: [
            <Button type="primary" key="primary">
              新建接口
            </Button>,
          ],
        }}
      />

      <InterfaceInfoDrawer
        currentInterfaceDetail={interfaceInfo}
        openDrawer={openDrawer}
        closeDrawer={()=>setOpenDrawer(false)}
      />

      <Modal okText={'立即申请'} title={currentInterfaceDetail?.name} open={isApplyModalOpen} onOk={handleApplyOk} onCancel={handleApplyCancel}>
        <Checkbox onChange={(e)=> {
          setIsAgree(e.target.checked)
        }}>我已阅读并同意</Checkbox>
      </Modal>

    </PageContainer>
  );
};
